<?php

namespace app\queue\redis\push_page;

use app\exception\ApiException;
use app\extensions\lib\FcmAccessToken;
use app\extensions\lib\push\AndroidPush;
use app\extensions\lib\push\BasePush;
use app\extensions\lib\push\HmsPush;
use app\extensions\lib\push\IosPush;
use app\extensions\lib\push\Push;
use app\model\TokenInfo;
use support\Db;
use support\Log;
use Webman\RedisQueue\Consumer;
use Webman\RedisQueue\Redis;
class PagePush implements Consumer
{
    // 要消费的队列名
    public $queue = 'page_push_queue';
    public static $update_redis_queue_key = 'page_push_queue';
    public $connection = 'default';



    // 消费
    public function consume($data)
    {
        $page = $data['page'] ?? 0;
        $userData = $data['userData'] ?? [];
        $message = $data['message'] ?? [];
        $request_id = $data['request_id'] ?? '';
        $info = $data['info'] ?? '';
        $channel = $userData['channel'] ?? '';
        $TokenInfo = new TokenInfo();
        $userList = $TokenInfo->getUserList($userData,$page);
        $PublicPush = new \app\extensions\lib\push\Push();

        $recall = false;
        if(BasePush::isRequestRecall($request_id)){
            $recall = true;
        }

        if($this->checkEmpty($userList) || $recall){
            //不能标识为完成，因为异步队列不一定完成。继续推送一条空的数据在队列(队列是同步的
            $status = Redis::send(\app\queue\redis\push\Push::$update_redis_queue_key,
                ['request_id'=>$request_id,'cate_id'=>$userData['cate_id']??0,'is_finish'=>true,'channel'=>$channel],1);
            return true;
        }

        //渠道判断
        if(in_array($channel,Push::PUSH_UDID_URL)){
            foreach ($userList as $cos_id => $packageList){
                foreach ($packageList as $pid => $item){
                    Push::saveUidUrl($request_id,$item['udids']);//记录推送的udid
                }

            }
        }


        $pageInfo = $info.'-pagePush:page:'.$page;

        $results = $PublicPush->push($userList,$message,true,$request_id,[],$pageInfo);
        Log::channel('request')->info($request_id.':page_push:'.$page.':'.json_encode($data).'::'.json_encode($results));


        $page++;
        $data['page'] = $page;
        $status = intval(Redis::send($this->queue,$data));

    }

    private function checkEmpty(array $userList)
    {
        $isEmpty = true;
        foreach ([1,2,3] as $os_id){
            if(!empty($userList[$os_id])){
                $isEmpty = false;
                break;
            }
        }
        return $isEmpty;

    }
}